# This file is part of Gehyra.
#
# Gehyra is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Gehyra is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Gehyra.  If not, see <http://www.gnu.org/licenses/>.

"""
@package gehyra.config.locations
Object for managing all configuration data.
Manages the configuration files available to the node.
$Id: locations.py 450 2011-01-20 14:28:47Z andyhhp@gmail.com $
"""

"""
@file gehyra/config/locations.py
Object for managing all configuration data.
Manages the configuration files available to the node.
"""

from gehyra.common.util import get_user_path
from os.path import isfile, abspath, splitext, basename

def get_node_path(node_cfg):
    """
    Return a path, given a node config path or name.
    """
    if not node_cfg:
        return get_user_path("node.cfg")

    path = abspath(node_cfg)
    if isfile(path):
        return path

    path = get_user_path(node_cfg+".cfg")
    if isfile(path):
        return path

    return node_cfg if node_cfg.endswith(".cfg") else path


def get_network_path(network_cfg):
    """
    Return a path, given a network config path or name.
    """
    return get_config_path(network_cfg, "network")

def get_bridge_path(bridge_cfg):
    """
    Return a path, given a bridge config path or name.
    """
    return get_config_path(bridge_cfg, "bridge")


def get_config_path(cfg, prefix):
    """
    Return a path, given a config path or name, and prefix

    @param cfg Path or name of config
    @param prefix The subdir of ~ to search in
    """
    if not cfg:
        return None

    path = abspath(cfg)
    if isfile(path):
        return path

    path = get_user_path("%s/%s.cfg" % (prefix, cfg))
    if isfile(path):
        return path

    path = get_user_path("%s/%s.id" % (prefix, cfg))
    if isfile(path):
        return path

    return cfg if cfg.endswith(".cfg") else path


def get_node_paths(node_path):
    """
    Return defaults names, given a path.
    """
    # root, ext = splitext(node_path)
    root, _ = splitext(node_path)
    return basename(root), root+".db", root+".log"
